import os
import re
import socket
import subprocess


def get_BATCH_INSTALL_ROOT():
  assert "BATCH_INSTALL_ROOT" in os.environ
  BATCH_INSTALL_ROOT = os.environ["BATCH_INSTALL_ROOT"]
  return BATCH_INSTALL_ROOT


def get_wrt_BATCH_INSTALL_ROOT(path):
  return os.path.join(get_BATCH_INSTALL_ROOT(), path)


def get_presto_repo_ROOT():
  return os.path.normpath(get_wrt_BATCH_INSTALL_ROOT("../"))


def get_nfs_path_impl(hostname):
  if hostname.endswith("iosg.corp.prestolabs.io"):
    return "/remote/iosg"
  elif hostname.endswith("sg.corp.prestolabs.io"):
    return "/remote/iosg"
  elif hostname.endswith("eqsh.corp.prestolabs.io"):
    return "/remote/eqsh"
  elif hostname.endswith("sh.corp.prestolabs.io"):
    return "/remote/eqsh"
  else:
    return None


def get_nfs_root(allow_fallback=False):
  hostname = socket.getfqdn()
  nfs_root = get_nfs_path_impl(hostname)
  if nfs_root is None:
    # best way to get host's hostname is via env variable
    # https://stackoverflow.com/questions/29808920/how-to-get-the-hostname-of-the-docker-host-from-inside-a-docker-container-on-tha
    host_hostname = os.getenv('HOST_HOSTNAME')
    if host_hostname is not None:
      nfs_root = get_nfs_path_impl(host_hostname)
  if nfs_root is not None:
    return nfs_root
  elif allow_fallback:
    return "/remote/iosg"
  else:
    raise ValueError("Not supported host: %s" % hostname)


def get_nfs_path(path):
  return os.path.join(get_nfs_root(), path)


def remove_prefix(text, prefix):
  if text.startswith(prefix):
    return text[len(prefix):]
  return text  # or whatever


def replace_nfs_path(path):
  if path.startswith("/remote/iosg/"):
    try:
      rpath = remove_prefix(path, "/remote/iosg/")
      return get_nfs_path(rpath)
    except ValueError:
      return path
  elif path.startswith("/remote/eqsh/"):
    try:
      rpath = remove_prefix(path, "/remote/eqsh/")
      return get_nfs_path(rpath)
    except ValueError:
      return path
  else:
    raise ValueError("Not supported path: %s" % path)


def get_nfs_temp_path(path, home_root=None, remove_abs_path=False):
  # TODO: set iosg/eqsh, make a better way getting home directory
  home_root = home_root or get_nfs_root()
  base_tmp_root = os.path.expanduser("~")
  if base_tmp_root.startswith("/"):
    base_tmp_root = base_tmp_root[1:]
  if remove_abs_path and path.startswith("/"):
    path = path[1:]
  return os.path.join(home_root, base_tmp_root, path)


def _remove_ansi_escape(text):
  ansi_escape = re.compile(r'\x1b[^m]*m')
  return ansi_escape.sub('', text)


def get_repo_status():
  repo_status = subprocess.check_output(
      "cd $(git rev-parse --show-toplevel) && env -i ./repo status", shell=True)
  repo_status = _remove_ansi_escape(repo_status.decode("utf-8"))
  return repo_status
